package lee.vioson.remotedata.repositories

import android.content.Context
import kotlinx.coroutines.flow.Flow
import kotlinx.coroutines.flow.flow
import lee.vioson.remotedata.ApiServices
import lee.vioson.remotedata.bean.LoginResult
import lee.vioson.remotedata.manager.UserManager
import lee.vioson.remotedata.utils.body

/**
 *Author:viosonlee
 *Date:2023/6/10
 *DESCRIPTION:
 */
class LoginRepositoryImpl(private val context: Context,private val apiServices: ApiServices) : LoginRepository,
    BaseRepository() {
    override fun anonymousLogin(uniqueId: String, customerSource: String) = flow {
        val loginResult = handleNotEmptyResponse(
            apiServices.anonymousLogin(
                mapOf(
                    "uniqueId" to uniqueId,
                    "customerSource" to customerSource,
                ).body
            )
        )
        UserManager.INSTANCE.saveAnonymousLoginResult(context, loginResult)
        emit(loginResult)
    }

    override fun login(
        uniqueId: String,
        email: String,
        password: String,
        loginType: Int
    ) = flow {
        val loginResult = handleNotEmptyResponse(apiServices.login(mapOf(
            "uniqueId" to uniqueId,
            "email" to email,
            "password" to password,
            "loginType" to loginType,
        ).body))
        UserManager.INSTANCE.saveEmailLoginResult(context, loginResult)
        emit(loginResult)
    }
}